<script>
import { sendHeartbeatMessage, pushLocation, getSocket, initWebSocket } from '@/utils/ws';
import config from '@/config';
export default {
	data() {
		return {
			wsTimer: null, // 用于存储心跳定时器ID
			timers: [],
			platform: '', // 登录设备信息
			locationPushTimer: null // 坐标推送定时器
		};
	},
	onLaunch: async function () {
		const areaData = uni.getStorageSync('areaData');
		if (!areaData) {
			const data = await this.$http.post('/h5/common/areasByLevel', params);
			uni.setStorageSync('areaData', data.data);
		}

		uni.removeStorageSync('firstIosUrl');
		// 如果是ios环境，则存储首次进入页面的url,用于微信分享
		if (uni.getSystemInfoSync().platform === 'ios') {
			if (!uni.getStorageSync('firstIosUrl')) {
				let firstIosUrl = window.location.href.split('#')[0];
				uni.setStorageSync('firstIosUrl', firstIosUrl.replace('index.html', ''));
			}
		}
		// 获取当前设备信息
		const systemInfo = uni.getSystemInfoSync();
		this.platform = systemInfo.platform;
	},
	onHide() {
		// 应用进入后台时清除定时器
	},
	onUnload() {
		// 页面卸载时清除定时器
		if (this.wsTimer) {
			clearInterval(this.wsTimer);
			this.wsTimer = null;
		}
		// 清除坐标推送定时器
		this.stopLocationPush();
	},
	onLoad(options) {
		console.log(110, 'APP.vue', options);
		// 获取当前设备信息
		const systemInfo = uni.getSystemInfoSync();
		let platform = systemInfo.platform;
		//如果是ios 则刷新页面，解决分享失败问题
		if (platform === 'ios' && !sessionStorage.getItem('hasReloaded')) {
			sessionStorage.setItem('hasReloaded', '1');
			location.reload();
			return;
		}
		sessionStorage.removeItem('hasReloaded');
	},
	onShow: function () {
		// 获取当前用户信息
		const userInfo = uni.getStorageSync('userInfo');

		if (!Window.wx) {
			// 全局加载微信SDK
			const script = document.createElement('script');
			script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
			script.onload = () => {
				wx.ready(() => {
					// 启动坐标推送定时任务
					this.startLocationPush(userInfo);
				});
			};
			document.head.appendChild(script);
		} else {
			wx.ready(() => {
				// 启动坐标推送定时任务
				this.startLocationPush(userInfo);
			});
		}

		// 页面刷新之后立即执行一次WS处理
		this.wsTimerDo(userInfo);

		// 每个五秒钟 发送一次心跳数据
		if (!this.wsTimer) {
			this.wsTimer = setInterval(() => {
				this.wsTimerDo(userInfo);
			}, 20000);
		}
	},

	onHide: function () {},
	methods: {
		// 心跳数据定时器
		wsTimerDo(userInfo) {
			if (!userInfo) return;
			// 获取socket对象
			let socket = getSocket();
			// 页面刷新之后，原有的socket对象已经失效，需要重新建立连接
			if (!socket || socket.readyState !== 1) {
				initWebSocket(userInfo.id);
			} else {
				// 用户登录之后，定时发送心跳数据
				sendHeartbeatMessage(userInfo.id);
			}
		},
		// 获取当前坐标
		getCurrentLocation(userInfo) {
			if (!userInfo) return;
			wx.getLocation({
				type: 'gcj02',
				isHighAccuracy: true, // 开启高精度定位
				highAccuracyExpireTime: 3000, // 高精度定位超时时间（毫秒）
				success: (res) => {
					const longitude = res.longitude;
					const latitude = res.latitude;
					// 推送坐标到服务器
					pushLocation(userInfo.id, userInfo.phone, userInfo.avatar_full, longitude, latitude);
				},
				fail: (res) => {
					console.log('定位失败：', res);
				},
				complete: (res) => {
					if (res.errMsg !== 'getLocation:ok') {
						console.log('定位失败：', res);
					}
				}
			});
		},
		// 启动坐标推送定时任务
		startLocationPush(userInfo) {
			if (!userInfo) return;
			// 先清除旧的定时器
			this.stopLocationPush();

			// 立即获取一次坐标
			this.getCurrentLocation(userInfo);

			// 每隔3秒推送一次坐标
			this.locationPushTimer = setInterval(() => {
				this.getCurrentLocation(userInfo);
			}, 3000);
		},
		// 停止坐标推送定时任务
		stopLocationPush() {
			if (this.locationPushTimer) {
				clearInterval(this.locationPushTimer);
				this.locationPushTimer = null;
			}
		}
	}
};
</script>

<style lang="scss">
@import 'uview-ui/index.scss';
@import url('/static/f.css');
page {
	background-color: #f5f5f5;
}

.common-btn {
	text-align: center;
	border-radius: 16rpx;
	height: 88rpx;
	line-height: 88rpx;
	background: linear-gradient(90deg, #ff3f39 0%, #ff7937 100%);
	color: #fff;
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 500;
	font-size: 32rpx;
	color: #ffffff;
}

/* 单行文本溢出 */
.ellipsis {
	white-space: nowrap;
	/* 禁止换行 */
	overflow: hidden;
	/* 隐藏溢出内容 */
	text-overflow: ellipsis;
	/* 显示省略号 */
	width: 180rpx;
	/* 设置固定宽度 */
}

/* #ifdef H5 */
// uni-page-head {
// display: none;
// }
/* #endif */

/* #ifdef H5 */
.u-slide-up-enter-active {
	border-radius: 26rpx 26rpx 0 0 !important;
	height: 680rpx !important;
	max-height: 680rpx !important;
	overflow: hidden !important;
}

/* #endif */
.u-picker__view__column__item {
	height: 72rpx !important;
	line-height: 72rpx !important;
}

/* 推荐写法 */
body .u-picker__view__column__item {
	height: 72rpx !important;
	line-height: 72rpx !important;
	color: #0b1f20 !important;
	/* 示例：自定义颜色 */
	font-size: 28rpx !important;
	background: #f5f5f5 !important;
}

.uni-picker-view-indicator,
.u-picker__indicator {
	height: 72rpx !important;
	line-height: 72rpx !important;
}

.u-toolbar {
	height: 100rpx !important;
	max-height: 100rpx !important;
}

.u-toolbar__wrapper__confirm {
	color: #ff7937 !important;
}

.u-search__action {
	background-color: transparent !important;
}

.uni-input-input {
	color: #0b1f20 !important;
}

.uni-textarea-textarea {
	color: #0b1f20 !important;
}
</style>
